package com.bawei.auth.service;

import com.bawei.common.core.constant.Constants;
import com.bawei.common.core.constant.SecurityConstants;
import com.bawei.common.core.constant.UserConstants;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.mall.user.api.RemoteCusUserService;
import com.bawei.mall.user.domain.CusUser;
import com.bawei.mall.user.domain.model.CusLoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName CusLoginService
 * @Description 描述
 * @Author ZiZheng.Li
 * @Date 2024/6/28 14:22
 */
@Component
public class CusLoginService {

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RemoteCusUserService remoteCusUserService;


    @Autowired
    private CusPasswordService passwordService;

    public CusLoginUser ssoLogin(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // 查询用户信息
        R<CusUser> cusLoginUser = remoteCusUserService.getUserInfo(username, SecurityConstants.INNER);
        if (StringUtils.isNull(cusLoginUser) || StringUtils.isNull(cusLoginUser.getData()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == cusLoginUser.getCode())
        {
            throw new ServiceException(cusLoginUser.getMsg());
        }
        CusLoginUser userInfo = new CusLoginUser();
        userInfo.setCusUser(cusLoginUser.getData());
        CusUser user = cusLoginUser.getData();
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }
}
